﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.SoldierArchives.BLL;
using Yipusoft.SoldierArchives.Model;
using System.IO;
using Microsoft.Office.Interop.Word;
using Yipusoft.Common.BLL;
using Yipusoft.Account.Model;

public partial class Police_TranslateDocument_IntroduceLetterNew : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bind();
        }
    }

    void Bind()
    {
        BindNewDepartment();
        if (Request["Fid"] == null)
            return;
        TranslateInfo TInfo = Translate.GetDetail(new Guid(Request["Fid"]));
        lblName1.Text = lblName.Text = TInfo.SoldierName;
        lblYear1.Text = lblYear.Text = DateTime.Now.Year.ToString();
        lblNo1.Text = No.Text = TranslateIntroLetter.GetNewNumber(TInfo.TID).ToString();
        lblSex2.Text = lblSex.Text = lblSex2.Text = TInfo.Sex;
        lblEnrollmentDate.Text = DateArmy.Text = TInfo.DateArmy.Year == 9999 ? "" : TInfo.DateArmy.ToString("yyyy年M月d日");

        lblRanker1.Text = lblRanker.Text = TInfo.Ranker;
        //lblNewDepartment.Text = lblDepartment.Text = TInfo.NewDepartment;
        //lblDate.Text = ConvertNumber(DateTime.Now.ToString("yyyy年M月d日"));
        lblOldDepartment.Text = TInfo.OldDepartment;
        lblOldDepartment2.Text = TInfo.OldDepartment2;
        DateTranslate.Text = DateTime.Now.ToShortDateString();
        DateRegister.Text = DateTime.Now.AddDays(3).ToShortDateString();
        lblDateRegister.Text = Convert.ToDateTime(DateRegister.Text).ToString("yyyy年M月d日");
        //lblDate.Text = ConvertNumber(TInfo.DateLastModefy.ToString("yyyy年M月dd日"));
        txtDateBook.Text = DateTime.Now.ToShortDateString();
        if (TInfo.SID != Guid.Empty)
        {
            Soldier soldier = new Soldier();
            SoldierArchiveInfo Sinfo = soldier.GetSoldierInfoByID(TInfo.SID.ToString());
            txtDuty.Text = CodeItem.GetCodeItem(Sinfo.Duty) != null ? CodeItem.GetCodeItem(Sinfo.Duty).ItemName : "";
        }
        if (TInfo.TID == 1)
        {
            ddlNewDepartment.Visible = true;
        }
        else
        {
            lblNewDepartment2.Visible = true;
            lblNewDepartment2.Text = TInfo.NewDepartment;
            lblNewDepartment.Text = TInfo.NewDepartment;
        }
        lblTakeType.Text = ddlTakeType.Text;
        Undertaker.Text = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName;
    }

    private void BindNewDepartment()
    {
        ddlNewDepartment.DataSource = GetDepartmentList();
        ddlNewDepartment.DataBind();
        lblNewDepartment.Text = ddlNewDepartment.SelectedItem.Text;
    }

    public List<DepartmentInfo> GetDepartmentList()
    {

        List<DepartmentInfo> departmentList = new List<DepartmentInfo>();
        departmentList = Yipusoft.Account.BLL.Department.GetList("Right(DepartmentID,2)='00'");
        return departmentList;
    }

    private string ConvertNumber(string Number)
    {

        string[] BigNumber = new string[] { "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十", "三十一", "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        string[] SmallNumber = new string[] { "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        string ReturnStr = string.Empty;
        for (int i = 0; i < 10; i++)
        {
            Number = Number.Replace(SmallNumber[i], BigNumber[i]);
        }
        return ConvertNumber1(Number);
    }

    private string ConvertNumber1(string Number)
    {

        string[] BigNumber = new string[] { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        string[] SmallNumber = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        string ReturnStr = string.Empty;
        for (int i = 0; i < 10; i++)
        {
            Number = Number.Replace(SmallNumber[i], BigNumber[i]);
        }
        return Number;
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        #region  验证
        DateTime EDate = new DateTime();
        if (!DateTime.TryParse(DateRegister.Text, out EDate))
        {
            Prompt.Text = "提示：报到时间格式不正确！";
            return;
        }
        if (!DateTime.TryParse(txtDateBook.Text, out EDate))
        {
            Prompt.Text = "提示：时间格式不正确！";
            return;
        }
        //扩展名
        string ex = "";
        if (!WordFile.HasFile)
        {
            //Prompt.Text = "提示：请上传对方介绍信！";
            //return;
        }
        else
        {
            ex = WordFile.FileName.Substring(WordFile.FileName.LastIndexOf('.') + 1);
            if (ex.ToLower() != "jpg" && ex.ToLower() != "bmp" && ex.ToLower() != "gif")
            {
                Prompt.Text = "提示:上传必须为图片!";
                return;
            }
            if (WordFile.FileContent.Length / 1024 / 1024 > 5)
            {
                Prompt.Text = "提示:上传文档不可大于5M!";
                return;

            }
        }
        #endregion

        TranslateInfo translate = Translate.GetDetail(new Guid(Request["Fid"]));
        #region 添加士兵
        if (translate.TID == 1)
        {
            SoldierArchiveInfo soldierInfo = new SoldierArchiveInfo();
            AssignSoldierInfo(soldierInfo);
            soldierInfo.SoldierName = translate.SoldierName;
            soldierInfo.Sex = translate.Sex;
            soldierInfo.DepartmentID = translate.ToDepartmentID;
            Soldier soldier = new Soldier();
            Guid soldierID = soldier.Insert2(soldierInfo, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName);
            translate.SID = soldierID;
            Translate.Update(translate);
        }


        #endregion

        #region 添加对方介绍信
        TranslateIntroFileInfo fileInfo = new TranslateIntroFileInfo();
        if (!WordFile.HasFile)
        {
        }
        else
        {
            string word = DateTime.Now.ToString("yyyyMMddhhmmssfff") + "." + ex;
            string path = Server.MapPath("..\\TranslateDocument\\WordFile\\");
            WordFile.SaveAs(path + word);
            fileInfo.PilePath = word;
        }


        fileInfo.DateBook = DateTime.Now;


        fileInfo.Bookmen = User.Identity.Name;
        Guid id = TranslateIntrolFile.Insert(fileInfo);

        TranslateInfo TranslateInfo = Translate.GetDetail(new Guid(Request.QueryString["Fid"]));
        TranslateLogInfo log = new TranslateLogInfo();
        log.DID = id;
        log.FID = TranslateInfo.ID;
        log.LastTime = DateTime.Now;
        log.PID = TranslateProcess.GetNextDetail(TranslateLogs.GetLastDetail(TranslateInfo.ID).PID).ID;
        TranslateLogs.Insert(log);

        #endregion


        TranslateIntroLetterInfo info = new TranslateIntroLetterInfo();

        #region 添加介绍信
        info.ApproveMan = ApproveMan.Text;
        info.Bookman = User.Identity.Name;
        info.DateArmy = DateArmy.Text == "" ? DateTime.MaxValue : Convert.ToDateTime(DateArmy.Text);
        info.DateBook = Convert.ToDateTime(txtDateBook.Text);
        info.DateRegister = Convert.ToDateTime(DateRegister.Text);
        info.Duty = txtDuty.Text;
        info.Linkman = Linkman.Text;
        info.NewDepartment = lblNewDepartment.Text;
        info.Number = Convert.ToInt32(No.Text);
        info.OldDepartment = lblOldDepartment.Text;
        info.Ranker = lblRanker.Text;
        info.Remark = Remark.Text;
        info.Sex = lblSex.Text;
        info.SoldierName = lblName.Text;
        info.TimeLastModified = DateTime.Now;
        info.TimeLimit = 0;
        info.Undertaker = Undertaker.Text;
        info.UserLastModified = User.Identity.Name;
        info.YearNo = lblYear.Text;
        info.TakeType = ddlTakeType.SelectedValue;
        info.OldDepartment2 = lblOldDepartment2.Text;
        Guid Lid = TranslateIntroLetter.Insert(info);
        log = new TranslateLogInfo();
        log.DID = Lid;
        log.FID = new Guid(Request["FID"]);
        log.LastTime = DateTime.Now;
        TranslateInfo TInfo = Translate.GetDetail(new Guid(Request["Fid"]));
        log.PID = TranslateProcess.GetNextDetail(TranslateLogs.GetLastDetail(TInfo.ID).PID).ID;
        TranslateLogs.Insert(log);

        #endregion
        #region 修改为调往支队
        if (translate.TID == 1)
        {
            translate.NewDepartment = ddlNewDepartment.SelectedItem.Text;
            translate.ToDepartmentID = ddlNewDepartment.SelectedValue;
            Translate.Update(translate);
        }
        #endregion
        lblID.Text = Lid.ToString();
        BtnPrint.CommandName = Lid.ToString();

        #region 士兵调动操作
        info = TranslateIntroLetter.GetDetail(new Guid(lblID.Text));
        string transferID = "";
        if (!String.IsNullOrEmpty(Request["TID"]))
            transferID = Request["TID"];
        string UserName = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName;
        TranslateInfo Info = Translate.GetDetail(new Guid(Request.QueryString["Fid"].ToString()));
        Guid trid = Guid.Empty;
        if (Info.TID == 1)//调入
        {
            trid = TransferSoldier.Transfer(Info.SID.ToString(), Info.FromDepartmentID, Info.OldDepartment, Info.ToDepartmentID, Info.NewDepartment, Convert.ToDateTime(DateTranslate.Text), User.Identity.Name, UserName, DateTime.Now, Info.FromJingZhong, Info.ToJingZhong, info.DateRegister, info.ApproveMan, "");
            if (trid != Guid.Empty)
            {
                Soldier soldier = new Soldier();
                SoldierArchiveInfo soldierInfo = soldier.GetSoldierInfoByID(Info.SID.ToString());
                soldierInfo.DepartmentID = Info.ToDepartmentID;
                soldier.Update(soldierInfo, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName);
            }
            else
            {
                Prompt.Text = "提示：调动失败！";
            }
        }
        else if (Info.TID == 2)//调出
        {
            trid = TransferSoldier.Transfer(Info.SID.ToString(), Info.FromDepartmentID, Info.OldDepartment2, Info.ToDepartmentID, Info.NewDepartment, Convert.ToDateTime(DateTranslate.Text), User.Identity.Name, UserName, DateTime.Now, Info.FromJingZhong, Info.ToJingZhong, info.DateRegister, info.ApproveMan, "");
            if (trid != Guid.Empty)
            {
                Soldier soldier = new Soldier();
                soldier.Delete(Info.SID.ToString(), "调离", DateTime.Now, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName);
            }
        }
        else if (Info.TID == 3)//内调
        {
            trid = TransferSoldier.Transfer(Info.SID.ToString(), Info.FromDepartmentID, Info.OldDepartment2, Info.ToDepartmentID, Info.NewDepartment, Convert.ToDateTime(DateTranslate.Text), User.Identity.Name, UserName, DateTime.Now, Info.FromJingZhong, Info.ToJingZhong, info.DateRegister, info.ApproveMan, "");
            if (trid != Guid.Empty)
            {
                Soldier soldier = new Soldier();
                SoldierArchiveInfo soldierInfo = soldier.GetSoldierInfoByID(Info.SID.ToString());
                soldierInfo.DepartmentID = Info.ToDepartmentID;
                soldier.Update(soldierInfo, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName);
            }
        }

        log = new TranslateLogInfo();
        log.DID = trid;
        log.FID = new Guid(Request["FID"]);
        log.LastTime = DateTime.Now;
        TInfo = Translate.GetDetail(new Guid(Request["Fid"]));
        log.PID = TranslateProcess.GetNextDetail(TranslateLogs.GetLastDetail(TInfo.ID).PID).ID;
        TranslateLogs.Insert(log);

        #endregion
        Prompt.Text = "提示：调动完成。";
        Button1.Visible = false;
        Button2.Visible = true;
        BtnPrint.Visible = true;
        //不可编辑状态
        ddlNewDepartment.Enabled = false;
        DateRegister.Enabled = false;
        ddlTakeType.Enabled = false;
        ApproveMan.Enabled = false;
        Linkman.Enabled = false;
        Remark.Enabled = false;
        Undertaker.Enabled = false;
        txtDuty.Enabled = false;
        WordFile.Enabled = false;
        DateTranslate.Enabled = false;

    }

    protected void BtnPrint_Click(object sender, EventArgs e)
    {
        if (BtnPrint.CommandName.Trim() == "")
            return;

        Print(BtnPrint.CommandName.ToString());
    }
    protected void killAllProcess() // 杀掉所有winword.exe进程
    {
        System.Diagnostics.Process[] myPs;
        myPs = System.Diagnostics.Process.GetProcesses();
        foreach (System.Diagnostics.Process p in myPs)
        {
            if (p.Id != 0)
            {
                string myS = "WINWORD.EXE" + p.ProcessName + "  ID:" + p.Id.ToString();
                try
                {
                    if (p.Modules != null)
                        if (p.Modules.Count > 0)
                        {
                            System.Diagnostics.ProcessModule pm = p.Modules[0];
                            myS += "\n Modules[0].FileName:" + pm.FileName;
                            myS += "\n Modules[0].ModuleName:" + pm.ModuleName;
                            myS += "\n Modules[0].FileVersionInfo:\n" + pm.FileVersionInfo.ToString();
                            if (pm.ModuleName.ToLower() == "winword.exe")
                                p.Kill();
                        }
                }
                catch
                { }
                finally
                {
                    ;
                }
            }
        }
    }
    private void Print(string StrID)
    {
        if (string.IsNullOrEmpty(StrID))
            return;
        Yipusoft.SoldierArchives.Model.TranslateIntroLetterInfo info = Yipusoft.SoldierArchives.BLL.TranslateIntroLetter.GetDetail(new Guid(StrID));

        if (info == null)
            return;
        killAllProcess();
        object oMissing = System.Reflection.Missing.Value;
        Microsoft.Office.Interop.Word._Application oWord;
        Microsoft.Office.Interop.Word._Document oDoc;
        string FileName2 = DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc";
        object Filename = @Server.MapPath("Doc/") + FileName2;
        //try
        //{
        object missing = System.Reflection.Missing.Value;
        object oTemplate = Server.MapPath("Template/IntroduceLetter.dot");
        oWord = new Microsoft.Office.Interop.Word.Application();
        oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);

        Object Nothing = System.Reflection.Missing.Value;
        object Visible = true;
        object ReadOnly = false;
        oWord.Visible = false;

        foreach (Microsoft.Office.Interop.Word.Bookmark bk in oDoc.Bookmarks)
        {
            switch (bk.Name)
            {

                case "YearID":
                    bk.Select();
                    bk.Range.Text = "[" + info.YearNo.ToString() + "]";
                    break;
                case "YearID2":
                    bk.Select();
                    bk.Range.Text = "[" + info.YearNo.ToString() + "]";
                    break;
                case "WordID":
                    bk.Select();
                    bk.Range.Text = info.Number.ToString();
                    break;
                case "WordID2":
                    bk.Select();
                    bk.Range.Text = info.Number.ToString();
                    break;
                case "Name":
                    bk.Select();
                    bk.Range.Text = info.SoldierName;
                    break;
                case "Name2":
                    bk.Select();
                    bk.Range.Text = info.SoldierName;
                    break;
                case "Take":
                    bk.Select();
                    bk.Range.Text = info.TakeType.ToString();
                    break;
                case "Sex":
                    bk.Select();
                    bk.Range.Text = info.Sex.ToString();
                    break;
                case "Sex2":
                    bk.Select();
                    bk.Range.Text = info.Sex.ToString();
                    break;
                case "OverDay":
                    bk.Select();
                    bk.Range.Text = info.DateRegister.ToString("yyyy年M月d日");
                    break;
                case "Duty":
                    bk.Select();
                    bk.Range.Text = info.Duty;
                    break;
                case "AmyDate2":
                    bk.Select();
                    bk.Range.Text = info.DateArmy.Year == 9999 ? "" : info.DateArmy.ToString("yyyy年M月d日");
                    break;
                case "Rank2":
                    bk.Select();
                    bk.Range.Text = info.Ranker;
                    break;
                case "MonthDay":
                    bk.Select();
                    bk.Range.Text = info.DateRegister.ToString("M月d日");
                    break;
                case "OldDepartment":
                    bk.Select();
                    bk.Range.Text = info.OldDepartment.ToString();
                    break;
                case "NewDepartment":
                    bk.Select();
                    bk.Range.Text = info.NewDepartment.ToString();
                    break;
                case "OldDepartment2":
                    bk.Select();
                    bk.Range.Text = info.OldDepartment.ToString();
                    break;
                case "NewDepartment2":
                    bk.Select();
                    bk.Range.Text = info.NewDepartment.ToString();
                    break;
                case "Department":
                    bk.Select();
                    bk.Range.Text = info.NewDepartment;
                    break;
                case "LinkMan":
                    bk.Select();
                    bk.Range.Text = info.Linkman.ToString();
                    break;
                case "Archives":
                    bk.Select();
                    bk.Range.Text = info.TakeType.ToString();
                    break;
                case "undertaker":
                    bk.Select();
                    bk.Range.Text = info.Undertaker.ToString();
                    break;
                case "ApproveMan":
                    bk.Select();
                    bk.Range.Text = info.ApproveMan;
                    break;
                case "Rank":
                    bk.Select();
                    bk.Range.Text = info.Ranker;
                    break;
                case "Remark":
                    bk.Select();
                    bk.Range.Text = info.Remark;
                    break;
                case "AmyDate":
                    bk.Select();
                    bk.Range.Text = info.DateArmy.Year == 9999 ? "" : info.DateArmy.ToString("yyyy年M月d日");
                    break;
                case "Date":
                    bk.Select();
                    bk.Range.Text = ConvertNumber(info.DateBook.ToString("yyyy年M月d日"));
                    break;
            }


        }

        object oFormat = WdSaveFormat.wdFormatDocument97;
        oDoc.SaveAs(ref Filename, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

        //    oWord.Documents.Open(ref Filename, ref missing, ref ReadOnly, ref missing,
        //ref missing, ref missing, ref missing, ref missing,
        //ref missing, ref missing, ref missing, ref Visible,
        //ref missing, ref missing, ref missing,
        //ref missing);
        //oDoc.PrintOut(ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
        //oDoc.PrintPreview();
        //openDocObj = new ActiveXObject("SharePoint.OpenDocuments.2");
        oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
        oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        //}
        //catch
        //{

        //};
        // Response.Redirect("http://10.24.10.13/Police/TranslateDocument/Doc/" + FileName2.ToString());
        string path = Filename.ToString();
        FileInfo file = new FileInfo(Filename.ToString());
        FileStream myfileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
        byte[] filedata = new Byte[file.Length];
        myfileStream.Read(filedata, 0, (int)(file.Length));
        myfileStream.Close();
        Response.Clear();
        Response.ContentType = "application/msword";
        Response.AddHeader("Content-Disposition", "attachment;filename=Report.doc");
        Response.Flush();
        Response.BinaryWrite(filedata);
        Response.End();
    }
    protected void ddlNewDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblNewDepartment.Text = ddlNewDepartment.SelectedItem.Text;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("../TranslateProcess/ProcessList.aspx");
    }

    private void AssignSoldierInfo(SoldierArchiveInfo soldierInfo)
    {
        soldierInfo.Background = "";
        soldierInfo.Birthday = DateTime.MinValue;
        soldierInfo.CardID = "";
        soldierInfo.ChooseID = "";
        soldierInfo.ConfirmID = "";
        soldierInfo.Culture = "";
        soldierInfo.DepartmentID = "";
        soldierInfo.Duty = "";
        soldierInfo.Height = 0;
        soldierInfo.HomePlace = "";
        soldierInfo.JoinPlace = "";
        soldierInfo.JoinTime = DateTime.MinValue;
        soldierInfo.Marriage = "";
        soldierInfo.Nation = "";
        soldierInfo.Native = "";
        soldierInfo.PartyTime = DateTime.MinValue;
        soldierInfo.Rank = ""; ;
        soldierInfo.RegisterID = ""; ;
        soldierInfo.Religion = "";
        soldierInfo.Sex = "";
        soldierInfo.SoldierName = "";
        soldierInfo.Speciality1 = "";
        soldierInfo.Speciality2 = "";
        soldierInfo.Status = "";
        soldierInfo.Weight = 0;
        soldierInfo.YouthTime = DateTime.MinValue;
        soldierInfo.IsContract = false;
        soldierInfo.Picture = "";
    }
    protected void ddlTakeType_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblTakeType.Text = ddlTakeType.Text;
    }
    protected void DateRegister_TextChanged(object sender, EventArgs e)
    {
        lblDateRegister.Text = Convert.ToDateTime(DateRegister.Text).ToString("yyyy年M月d日");
    }
}
